#include "filter_show.h"
#include "ui_filter_show.h"
#include "main_windw.h"
#include <QSettings>
#include <QComboBox>
#include <QJsonObject>
#include <QJsonDocument>
#include "cJSON.h"
#include "string.h"
#include "stdlib.h"

void Bytearry_to_arry(QByteArray Qbyte, uint8_t *buf, int len)
{
    if (len > Qbyte.length())
    {
        len = Qbyte.length();
    }

    for (int i = 0; i < len; i++)
    {
        buf[i] = Qbyte[i];
    }
}

void filter_show::put_data_to_widget(void)
{
    QString hexString;

    QByteArray data = table_json->Get_file_data();
    if (data == nullptr)
    {
        return;
    }
    cJSON *root = cJSON_Parse(data.data());
    if (!root)
    {
        return;
    }
    /*找到表有多少行*/
    cJSON *table_num = cJSON_GetObjectItem(root, "Protocol_table");
    if (!table_num)
    {
        return;
    }
    int max_table = table_num->valueint;

    if (max_table > LIST_ROW)
    {
        max_table = LIST_ROW;
    }
    /*查找list 取出list每一个*/
    cJSON *list = cJSON_GetObjectItem(root, "list");
    if (!list)
    {
        return;
    }

    for (int i = 0; i < max_table; i++)
    {
        /*把每个内容取出来放入表格*/
        cJSON *item = cJSON_GetArrayItem(list, i);
        if (!item)
        {
            continue;
        }

        QString name_str = "null";

        QString type_str = "null";

        /*查找 row*/
        cJSON *row = cJSON_GetObjectItem(item, "row");
        if (!row)
        {
            continue;
        }
        else
        {
            if (i != row->valueint)
            {
                /*确保行数匹配*/
                continue;
            }
        }
        /*查找name*/
        cJSON *name = cJSON_GetObjectItem(item, "name");
        if (name)
        {
            name_str = QByteArray(name->valuestring);
        }
        /*查找len*/
        cJSON *len = cJSON_GetObjectItem(item, "len");
        if (len)
        {
            protocol_arry[i] = len->valueint;
            qDebug() << "len:" << len->valuedouble << len->valueint;
        }
        /*查找type*/
        cJSON *type = cJSON_GetObjectItem(item, "type");
        if (type)
        {
            type_str = QByteArray(type->valuestring);
        }

        qDebug() << "find:" << row->valueint << name_str << protocol_arry[i] << type_str;
        if (protocol_arry[i] != 0)
        {
            qDebug() << "find :" << protocol_arry[i];
            /*放入name*/
            if (!name_str.contains("null"))
            {
                put_info_to_widget(i, PRO_NAME_INDEX, name_str, nullptr, true);
            }
            /*放入长度*/
            hexString = QString::number(protocol_arry[i]);
            put_info_to_widget(i, PRO_LEN_INDEX, hexString, nullptr, true);

            /*放入comboc 类型*/
            QComboBox *comboBox = new QComboBox();
            comboBox->addItems(type_items);

            comboBox->setCurrentIndex(type_items.indexOf(type_str));

            ui->tableWidget_show_info->setCellWidget(i, PRO_TYPE_INDEX, comboBox);
        }
    }

    cJSON_Delete(root);
}

filter_show::filter_show(QWidget *parent) : QWidget(parent),
                                            ui(new Ui::filter_show)
{
    ui->setupUi(this);

    connect(this, &filter_show::Update_filter_buf_signal, this, &filter_show::Update_filter_process);

    init_show_info();

    type_items << TYPE_UINT << TYPE_INT << TYPE_FLOAT;

    log_save = new Log_save(this, "log_info.txt");

    table_json = new File_save_get(this, "protocol_info.txt");

    put_data_to_widget();
}

filter_show::~filter_show()
{
    delete ui;
}
void filter_show::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    emit close_wid();
}

void Main_windw::filter_show_start(void)
{
    Filtershow = new filter_show();

    connect(Filtershow, &filter_show::close_wid, this, &Main_windw::filter_show_close_cb);

    Filtershow->show();
}

void filter_show::init_show_info(void)
{
    QStringList h_headerText;
    h_headerText << "数据" << "名字" << "长度(字节)" << "类型" << "HEX" << "Value";
    // v_headerText<<"数据"<<"数据"<<"数据"<<"数据";
    ui->tableWidget_show_info->setColumnCount(LIST_COLUM);
    ui->tableWidget_show_info->setRowCount(LIST_ROW);

    ui->tableWidget_show_info->setHorizontalHeaderLabels(h_headerText); // 横向表头
    // ui->tableWidget->setVerticalHeaderLabels(v_headerText);//竖向表头
    ui->tableWidget_show_info->horizontalHeader()->setVisible(true); // 设置表头可显示
#if 1
    ui->tableWidget_show_info->resizeColumnsToContents();
    ui->tableWidget_show_info->resizeRowsToContents();
    ui->tableWidget_show_info->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); // x先自适应宽度
    ui->tableWidget_show_info->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget_show_info->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
#endif
}

void filter_show::put_info_to_widget(uint32_t h_row, uint32_t h_colum, QString data, QColor h_color, uint8_t state)
{
    QTableWidgetItem *item;
    item = new QTableWidgetItem(data);
    if (!state)
    {
        item->setFlags(Qt::ItemFlags(false));
    }
    if (h_color != nullptr)
    {
        //        item->setTextColor(h_color); //旧版本弃用接口
        item->setForeground(h_color);
    }
    item->setTextAlignment(Qt::AlignCenter);                  // 设置内容居中
    ui->tableWidget_show_info->setItem(h_row, h_colum, item); // 添加项目到表格
}

void filter_show::Update_filter_buf(uint8_t *data, uint16_t lenth)
{
    for (int i = 0; i < lenth; i++)
    {
        data_buf[i] = data[i];
    }
    emit Update_filter_buf_signal(lenth);
}

void filter_show::Update_filter_process(int len)
{
    QString hexString;

    if (len > DATA_PACK_LEN)
    {
        len = DATA_PACK_LEN;
    }

    for (int i = 0; i < len; i++)
    {
        hexString = QString::asprintf("%02X", static_cast<unsigned char>(data_buf.at(i)));
        /*添加原始数据*/
        put_info_to_widget(i, 0, hexString, nullptr, true);

        if (protocol_arry[i] != 0)
        {

//            hexString = QString::number(protocol_arry[i]);
//            put_info_to_widget(i, 2, hexString, nullptr, true);

            switch (protocol_type_arry[i])
            {
                case E_TYPE_UINT:
//                    uint32_t data = 0;
//                    memcpy(&data,&data_buf[i],protocol_arry);
                break;
                case E_TYPE_INT:

                break;
                case E_TYPE_FLOAT:

                break;
                default:
                break;
            }
        }
    }

    // 更新数据到内容
    /*把数据放入用户自定义内容中显示*/
    show_user_data();

    data_buf.clear();
}
/*!
 *  @bref  从指定表格读取内容出来
 */
QString filter_show::read_param_from_widget(uint32_t h_row, uint32_t h_colum)
{
    QTableWidgetItem *h_item = ui->tableWidget_show_info->item(h_row, h_colum); // 指向表格item
    if (h_item == nullptr)
    {                   // 没有item返回空指针
        return nullptr; //
    }
    return h_item->text(); // 取出item内容
}

/*!
 *  @bref  从指定表格读取内容出来
 */
QWidget *filter_show::read_widget_from_widget(uint32_t h_row, uint32_t h_colum)
{
    QWidget *wid = ui->tableWidget_show_info->cellWidget(h_row, h_colum);

    if (wid == nullptr)
    {                   // 没有item返回空指针
        return nullptr; //
    }
    return wid; // 取出item内容
}

void filter_show::on_tableWidget_show_info_itemChanged(QTableWidgetItem *item)
{

    QString h_data;
    uint32_t h_column, h_row;
    //! 获取行列数
    h_column = item->column();
    h_row = item->row();

    if (h_column < LIST_COLUM && h_row < LIST_ROW)
    {
        //! 取出本行参数
        h_data = read_param_from_widget(h_row, h_column);
    }

    /*区分不同类型*/
    switch (h_column)
    {
    case PRO_LEN_INDEX:
        if (h_data != nullptr)
        {
            /*检查数据内容是否合理*/
            uint32_t num = h_data.toInt();
            qDebug() << "input :" << num;

            if ((num > (LIST_ROW - h_row)) || num == 0)
            {
                ui->tableWidget_show_info->removeCellWidget(h_row, PRO_TYPE_INDEX);
                //                ui->tableWidget_show_info->removeCellWidget(h_row, PRO_LEN_INDEX);
                put_info_to_widget(h_row, PRO_LEN_INDEX, 0, nullptr, true);
                return;
            }

            /*右侧添加数据对应的类型*/

            QComboBox *comboBox = new QComboBox();
            comboBox->addItems(type_items);
            ui->tableWidget_show_info->setCellWidget(h_row, PRO_TYPE_INDEX, comboBox);
        }
        else
        {
            ui->tableWidget_show_info->removeCellWidget(h_row, PRO_TYPE_INDEX);
        }
        break;
    case PRO_NAME_INDEX:
        if (h_data != nullptr)
        {
        }
        else
        {
        }
        break;
    case PRO_TYPE_INDEX:

        break;

    default:
        break;
    }
}
void swapEndianness(void *data, uint16_t size)
{
    uint8_t *bytes = (uint8_t *)data;
    uint8_t i;

    for (i = 0; i < size / 2; i++)
    {
        uint8_t temp = bytes[i];
        bytes[i] = bytes[size - 1 - i];
        bytes[size - 1 - i] = temp;
    }
}

int filter_show::get_checkBox_parse_recv_state(void)
{
    if (ui->checkBox_parse_recv->checkState() == Qt::Checked)
    {
        return 1;
    }
    return 0;
};

void filter_show::show_user_data(void)
{
    uint8_t data[DATA_PACK_LEN] = {0};
    uint32_t pres_min = 0;
    uint32_t pres_big = 0;

    uint32_t air_flow_min = 0;
    uint32_t air_flow_big = 0;

    uint8_t state_min;
    uint8_t state_big;

    if (data_buf.length() <= 16)
    {
        return;
    }

    for (int i = 0; i < data_buf.length(); i++)
    {
        data[i] = data_buf[i];
    }

    if (data[2] != 5)
    {
        return;
    }

    // 取出压力
    swapEndianness(&data[5], 4);
    memcpy(&pres_min, &data[5], sizeof(pres_min));

    // pu8DataBuf[9] = (pstUpInf->u32GasFlow1 & 0xFF00) >> 8;
    // pu8DataBuf[10] = pstUpInf->u32GasFlow1 & 0xFF;
    // pu8DataBuf[11] = (pstUpInf->u32GasFlow2 & 0xFF00) >> 8;
    // pu8DataBuf[12] = pstUpInf->u32GasFlow2 & 0xFF;
    swapEndianness(&data[9], 4);
    memcpy(&pres_big, &data[9], sizeof(pres_big));

    // pu8DataBuf[13] = pstUpInf->u8DCState1 & 0xFF;
    // pu8DataBuf[14] = pstUpInf->u8DCState2 & 0xFF;
    // pu8DataBuf[15] = pstUpInf->u8DCState3 & 0xFF;
    // pu8DataBuf[16] = pstUpInf->u8DCState4 & 0xFF;
    swapEndianness(&data[13], 4);
    memcpy(&air_flow_min, &data[13], sizeof(air_flow_min));

    // pu8DataBuf[17] = pstUpInf->u8DCState1 & 0xFF;
    // pu8DataBuf[18] = pstUpInf->u8DCState2 & 0xFF;
    // pu8DataBuf[19] = pstUpInf->u8DCState3 & 0xFF;
    // pu8DataBuf[20] = pstUpInf->u8DCState4 & 0xFF;
    swapEndianness(&data[17], 4);
    memcpy(&air_flow_big, &data[17], sizeof(air_flow_big));

    state_min = data[21];
    state_big = data[22];
    // 取出气流

    // 取出状态

    ui->lineEdit_show_pressuer_min->setText(QString::number(pres_min));
    ui->lineEdit_show_pressuer_big->setText(QString::number(pres_big));

    ui->lineEdit_air_flow_min->setText(QString::number(air_flow_min));
    ui->lineEdit_air_flow_big->setText(QString::number(air_flow_big));

    QString log;

    if (state_min == 0)
    {
        ui->lineEdit_show_state_min->setText("放气");
        log.append("小气囊 放气: " + QString::number(pres_min) + " 气流值: " + QString::number(air_flow_min));
    }
    else if (state_min == 1)
    {
        ui->lineEdit_show_state_min->setText("充气");
        log.append("小气囊 充气: " + QString::number(pres_min) + " 气流值: " + QString::number(air_flow_min));
    }
    else if (state_min == 2)
    {
        ui->lineEdit_show_state_min->setText("保持");
        log.append("小气囊 保持: " + QString::number(pres_min) + " 气流值: " + QString::number(air_flow_min));
    }

    if (state_big == 0)
    {
        ui->lineEdit_show_state_big->setText("放气");
        log.append("   大气囊 放气: " + QString::number(pres_big) + " 气流值: " + QString::number(air_flow_big));
    }
    else if (state_big == 1)
    {
        ui->lineEdit_show_state_big->setText("充气");
        log.append("   大气囊 充气: " + QString::number(pres_big) + " 气流值: " + QString::number(air_flow_big));
    }
    else if (state_big == 2)
    {
        ui->lineEdit_show_state_big->setText("保持");
        log.append("   大气囊 保持: " + QString::number(pres_big) + " 气流值: " + QString::number(air_flow_big));
    }

    emit log_save->Update_log_signal(log);
}
/*
 * 全部以字符的形式，将表格保存下来
 */
void filter_show::on_checkBox_perse_protocol_clicked(bool checked)
{
    if (checked)
    {
        uint32_t i = 0;

        // 创建一个新的cJSON对象
        cJSON *root = cJSON_CreateObject();
        // 创建一个数组来存储学生信息
        cJSON *pro_list = cJSON_CreateArray();

        cJSON_AddItemToObject(root, "list", pro_list);

        /*取出长度列表的值，转换成数组位置*/
        for (i = 0; i < LIST_ROW; i++)
        {

            /*取出名字字段*/
            QString name = read_param_from_widget(i, PRO_NAME_INDEX);
            /*取出长度字段*/
            QString len = read_param_from_widget(i, PRO_LEN_INDEX);
            /*取出类型字段*/
            QWidget *type = read_widget_from_widget(i, PRO_TYPE_INDEX);

            QString type_str;

            /*判断长度字段*/
            if (len != nullptr)
            {
                uint32_t num = len.toInt();
                if ((num < (LIST_ROW - i)) && (num != 0))
                {
                    protocol_arry[i] = num;
                }
                else
                {
                    protocol_arry[i] = 0;
                }
                qDebug() << "get :" << protocol_arry[i];
            }
            else
            {
                protocol_arry[i] = 0;
            }
            /*判断名字字段*/
            if (name != nullptr)
            {
            }
            else
            {
                name = "null";
            }
            /*获取类型字段*/
            if (type != nullptr)
            {
                QComboBox *box = (QComboBox *)type;
                int idx = box->currentIndex();
                protocol_type_arry[i] = idx + 1;
                qDebug() << "type:" << idx;
                type_str = box->currentText();
            }
            else
            {
                protocol_type_arry[i] = 0;
                type_str = "null";
            }

            // 对象到_JSON_数组中
            cJSON *row_goup = cJSON_CreateObject();
            cJSON_AddNumberToObject(row_goup, "row", i);
            cJSON_AddStringToObject(row_goup, "name", QByteArray(name.toUtf8()).data());
            cJSON_AddNumberToObject(row_goup, "len", protocol_arry[i]);
            cJSON_AddStringToObject(row_goup, "type", QByteArray(type_str.toUtf8()).data());
            cJSON_AddItemToArray(pro_list, row_goup);

            qDebug() << "add_len:" << protocol_arry[i];
        }

        // 添加多个信息
        cJSON_AddNumberToObject(root, "Protocol_table", i);
        // 生成JSON字符串
        const char *jsonString = cJSON_PrintUnformatted(root);
        qDebug() << QByteArray(jsonString);

        table_json->Save_file_data(QByteArray(jsonString), File_save_get::FILE_COVER);

        // 释放内存
        cJSON_Delete(root);
        free((void *)jsonString);
    }
}
